﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using AutoMapper.Mappers;
using My.Pattern.Builder;

namespace My.Common.AutoMapper
{
    /// <summary>
    /// AutoMapperBuilder which defines the method list to automatically map from Source to Destination class
    /// </summary>
    public class AutoMapperBuilder : IAutoMapperBuilder
    {
        #region Public Methods

        public D MapSourceToDestination<S, D>(S source)
            where S : class
            where D : class, new()
        {
            return MapSourceToDestination<S, D>(source, CreateMapping<S, D>);
        }

        public D MapSourceToDestination<S, D>(S source, Action<ConfigurationStore> function)
            where S : class
            where D : class, new()
        {
            var config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
            function(config);
            var engine = new MappingEngine(config);
            return engine.Map(source as S, new D());
        }

        public D MapSourceToDestination<S, D>(S source, Action<ConfigurationStore> function, D destination)
            where S : class
            where D : class
        {
            var config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
            function(config);
            var engine = new MappingEngine(config);
            return engine.Map(source as S, destination);
        }

        #endregion

        #region Private Methods

        private void CreateMapping<S, D>(ConfigurationStore config)
            where S : class
            where D : class
        {
            config.CreateMap<S, D>();
        }

        #endregion
    }
}
